import { Component, OnInit } from '@angular/core';
import { FadeInTop } from "../../shared/animations/fade-in-top.decorator";
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import {config} from '../../shared/smartadmin.config';
declare var $: any;

declare var BMap: any;
declare var BMapLib: any;
declare var BMAP_STATUS_SUCCESS: any;
declare var document: any;


@FadeInTop()
@Component({
	selector: 'sa-car-itinerary',
	templateUrl: './car-itinerary.component.html',
	styleUrls: ['./itinerary.css']
})
export class CarItineraryComponent implements OnInit {
	deviceId:string = '';
	
	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.deviceId = queryParams.deviceId;
			
			
		});
	}

	ngOnInit() {
		System.import('assets/js/distanceTool.js').then(()=>{
			
			
			this.pageEvent();
		})
		
	}


	pageEvent(){
	
	var that=this;
	var map = new BMap.Map("allmap",{enableMapClick: false});    // 创建Map实例
	var myDis = new BMapLib.DistanceTool(map,{"followText" : ' ',// 测距过程中，提示框文字, 
		"unit" : "metric", //测距结果所用的单位制，可接受的属性为"metric"表示米制和"us"表示美国传统单位, 
		"lineColor" : "#579AFC", //折线颜色, 
		"lineStroke" : 3, //折线宽度, 
		"opacity" : 0, //透明度, 
//		"lineStyle" : {String}, //折线的样式，只可设置solid和dashed, 
//		"secIcon" : {BMap.Icon}, //转折点的Icon, 
//		"closeIcon" : {BMap.Icon}, //关闭按钮的Icon, 
//		"cursor" : {String} 
		});//跟随的鼠标样式
	var mapSize;//全局变量  监听地图的缩放大小
	map.addEventListener("zoomend", function(){   
		mapSize=this.getZoom();
	});
	var driving = new BMap.DrivingRoute(map, {renderOptions:{map: map, autoViewport: true}});
	var pointArr=[];
	var viaArr=[];//途径点数组
	var output = 0;
	var allTime=0;
	var mapPosition='';
	var deviceId=this.deviceId;

	
	var searchComplete = function (results){
		if (transit.getStatus() != BMAP_STATUS_SUCCESS){
			return ;
		}
		var plan = results.getPlan(0);
		allTime += plan.getDuration(true);                //获取时间
		
		output += plan.getDistance(true);             //获取距离
	}
	var transit = new BMap.DrivingRoute(map, {renderOptions: {map: map},
		onSearchComplete: searchComplete,
		onPolylinesSet: function(){        
			setTimeout(function(){console.log('总路程：'+output+'共需：'+allTime)},"1000");
	}});
	map.centerAndZoom(new BMap.Point(113.46, 22.27), 9);  // 初始化地图,设置中心点坐标和地图级别

	map.setCurrentCity("深圳");          // 设置地图显示的城市 此项是必须设置的
	map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放

	//绘画轨迹过程中将坐标点记录；
	myDis.addEventListener("addpoint", function(e) {
		var  coordinate:any={};
		coordinate.x=e.point.lng;coordinate.y=e.point.lat;
		viaArr.push(coordinate);
		});
	//绘画轨迹后输出所有记录的途径点坐标
	myDis.addEventListener("drawend", function(e) {  
		if(viaArr.length<2){
			return;
		}
		var len=$('.itineraryGroup').children().length;//路线数量
		$('.nowItinerary').find('.itineraryPoint').remove();
		//$('.omit').remove();
		
		for(var i=0;i<viaArr.length;i++){
			if(i<3){
				var element='<li class="col-xs-12 itineraryPoint"><span class="col-xs-2">'+(i+1)+'</span><span class="col-xs-5 lng">'+viaArr[i].x+'</span><span class="col-xs-5 lat">'+viaArr[i].y+'</span></li>';
				$('.nowItinerary').append(element);
			}
			else{
				var element='<li class="col-xs-12 itineraryPoint hidden"><span class="col-xs-2">'+(i+1)+'</span><span class="col-xs-5 lng">'+viaArr[i].x+'</span><span class="col-xs-5 lat">'+viaArr[i].y+'</span></li>';
				$('.nowItinerary').append(element);
			}
			
		}
		$('.nowItinerary').append('<li class="col-xs-12 omit"><span class="col-xs-2">......</span></li>');
		viaArr=[];
	});

	$('.event').mouseenter(function(){
		$(this).addClass('hoverEvent').siblings().removeClass('hoverEvent');
	})
	$('.event').parent().mouseleave(function(){
		$('.hoverEvent').removeClass('hoverEvent');
	})
	$('.addItinerary').click(function(){
		if($('.nowItinerary').children().length<3||$('.nowItinerary').find('.itineraryName').val()==''){//判断条件，线的坐标点不能少于2并且线路名不能为空
			return;
		}
		deletePoint();
		if(mapPosition!==''){
			map.addOverlay(new BMap.Marker(mapPosition)); 
		}
		
		myDis.open();
		var len=$('.itineraryGroup').children().length;//路线数量

		$('.nowItinerary').removeClass('nowItinerary');

		var el='<ol class="row nowItinerary itineraryList"><li class="col-xs-12"><span class="col-xs-3 lineName">路线'+(len+1)+'</span> <span class="col-xs-3 lineNameSpan">名称:</span><input class="col-xs-5 itineraryName" /><span class="deleteItinerary">X</span></li></ol>';
		$('.itineraryGroup').append(el);
		
	})
	function getData(deviceId){
		
		$.ajax({
	       	type : "POST",
	        url : config.BaseURL+"station/linelist.html",
	        xhrFields: {
				withCredentials: true
			},
	        data : {deviceId : deviceId},
	        dataType : "json",
	        contentType : 'application/x-www-form-urlencoded;charset=utf-8', //设置请求头信息，编码为key/value格式（默认可不加） 
	        success : function(result) {
	           
	            
	            	var size = result.data.length;
	            
	            	
	            	if(size<1){
	            		myDis.open();
	            		return;
	            	}
	            
	            	$('.nowItinerary ').remove();
	            	for(var x=0;x<result.data.length;x++){
	            		var id=result.data[x].id//取出每条路线的id
	            		var name=result.data[x].name;//取出每条路线名
	            		var el='<ol class="row itineraryList" id="'+id+'"><li class="col-xs-12"><span class="col-xs-3 lineName">路线'+(x+1)+'</span> <span class="col-xs-3 lineNameSpan">名称:</span><input class="col-xs-5 itineraryName" value="'+name+'"/><span class="deleteItinerary">X</span></li>';
	            		var stationList=result.data[x].stationList;
	            		for(var l=0;l<stationList.length;l++){
	            			if(l<3){
	            				el=el+'<li class="col-xs-12 itineraryPoint"><span class="col-xs-2">'+(l+1)+'</span><span class="col-xs-5 lng">'+stationList[l][0]+'</span><span class="col-xs-5 lat">'+stationList[l][1]+'</span></li>';
	    	            		
	            			}
	            			else{
	            				el=el+'<li class="col-xs-12 itineraryPoint hidden"><span class="col-xs-2">'+(l+1)+'</span><span class="col-xs-5 lng">'+stationList[l][0]+'</span><span class="col-xs-5 lat">'+stationList[l][1]+'</span></li>';
	    	            
	            			}
	            			}
	            		var element=el+'<li class="col-xs-12 omit"><span class="col-xs-2">......</span></li></ol>';
	            		
		        		$('.itineraryGroup').append(element);
		        		$('.itineraryGroup').children().eq(0).addClass('nowItinerary').find('.deleteItinerary').remove();
	            	}
	            
	            	drawLine();
	            	
	            	
	        
	        },
	        error : function(errorMsg) {
	        	alert('服务器未响应,请稍后再试');
//	            layer.msg('服务器未响应,请稍后再试', {
//	                icon : 2
//	            });
	        }
	    });
}
	getData(deviceId);//获取数据
	$('.event').click(function(){
		$(this).addClass('selectEvent').siblings().removeClass('selectEvent');
		var  eventType=$(this).attr('class').split(' ')[1];
		
		if(eventType=='itinerary'){
		
			deletePoint();
			if(mapPosition!==''){
				map.addOverlay(new BMap.Marker(mapPosition)); 
			}
			
			myDis.open();
		}
		else if(eventType=='clear'){
			deletePoint();
			myDis.close();
		}
		
	})
	$('.itineraryGroup').delegate('.itineraryList','click',function(){
		if($('.nowItinerary').children().length<3||$('.nowItinerary').find('.itineraryName').val()==''){
			//判断条件，线的坐标点不能少于2并且线路名不能为空
			return;
		}
		//选中一条路线的事件
		deletePoint();
		$('.nowItinerary').removeClass('nowItinerary');
		$(this).addClass('nowItinerary');
		drawLine();
		
	})
	function deleteData(obj) {
	var list = new Array();
	
	list.push(obj);
	
	var url = "station/deleteline.html"
		$.ajax({
	        type : "POST",
	        url : config.BaseURL+url,
	        data : JSON.stringify(list),
   	        xhrFields: {
				withCredentials: true
			},
	        success : function(result) {
	        	console.log(result)
	            if (result.success) {
	            	var count = result.data;
//	            	layer.msg("路线删除成功", {
//	                    icon : 1
//	                });
	            	alert("路线删除成功");
	    			var that=$('.nowItinerary');
	    			//that.prev().addClass('nowItinerary');
	    			that.remove();
	    			
	    			$('.itineraryGroup').find('.lineName').each(function(index,obj){
	    				if(index<1){
	    					$(this).parent().parent().addClass('nowItinerary');
	    				}
	    				$(this).text('路线'+(index+1));
	    			})
	    			drawAllLine();
	            } else {
//	                layer.msg(result.message, {
//	                    icon : 5
//	                });
	                alert(result.message)
	            }
	        },
	        error : function(errorMsg) {
	        	alert('服务器未响应,请稍后再试')
//	            layer.msg('服务器未响应,请稍后再试', {
//	                icon : 2
//	            });
	        }
	    });
}
	var deleteItineraryEvent=function deleteItineraryEvent(){
	
		var modal = document.getElementById('modalBox');//获取模态框
		$('.itineraryGroup').delegate('.deleteItinerary','click',function(e){
		
			modal.style.display = 'block';
			$('.nowItinerary').removeClass('nowItinerary');
			$(this).parent().parent().addClass('nowItinerary ');
		})
		$('.ascertain').click(function(){
			modal.style.display = 'none';
			var deleteId=$('.nowItinerary').attr('id');
			if(!deleteId){
				var that=$('.nowItinerary');
    			that.prev().addClass('nowItinerary');
    			that.remove();
    			$('.itineraryGroup').find('.lineName').each(function(index,obj){
    				$(this).text('路线'+(index+1));
    			})
    			//如果未存进数据库则直接删除元素
				return;
			}
			deleteData(deleteId);
			})
			
		$('.cancel').click(function(){
				modal.style.display = 'none';
			})
	}
	deleteItineraryEvent();//允许删除
	function G(id) {
		return document.getElementById(id);
	}
	function showInfo(e){
		alert(e.point.lng + ", " + e.point.lat);	
	}
	function deletePoint(){
		pointArr=[];
		viaArr=[];//途径点数组
		allTime=0;
		output=0;
		map.clearOverlays();
		}
	function removeClick(){
		map.removeEventListener("click", showInfo);
	}
	var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
			{"input" : "suggestId"
			,"location" : map
		});

		ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
		var str = "";
			var _value = e.fromitem.value;
			var value = "";
			if (e.fromitem.index > -1) {
				value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			}    
			str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
			
			value = "";
			if (e.toitem.index > -1) {
				_value = e.toitem.value;
				value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			}    
			str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
			G("searchResultPanel").innerHTML = str;
			
		});
		var myValue;
		ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件和点击 
		var _value = e.item.value;
			console.log(_value);
			myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			console.log(myValue);
			G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
			
			console.log("onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue);
			setPlace();
		});
		document.onkeyup = function (e) {  
		        e = window.event;  
		    var code = e.charCode || e.keyCode;  
		    if (code == 13) {  
		    	myValue=G('suggestId').value;
		    	if(myValue!==''){
		    		setPlace();
		    	}
		    }  
		}  
		G('search').onclick=function(){
			myValue=G('suggestId').value;
	    	if(myValue!==''){
	    		setPlace();
	    	}
		}
		function setPlace(){
			map.clearOverlays();    //清除地图上所有覆盖物
			function myFun(){
				var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
				mapPosition=pp;
				map.centerAndZoom(pp, 18);
				map.addOverlay(new BMap.Marker(pp));    //添加标注
			}
			var local = new BMap.LocalSearch(map, { //智能搜索
			  onSearchComplete: myFun
			});
			local.search(myValue);
		}
		function postData(arr) {
		console.log(JSON.stringify(arr),'param')
				$.ajax({
					
					type : "POST",
			        url : config.BaseURL+"station/addline.html",
			        xhrFields: {
						withCredentials: true
					},
			        data : {"sss":JSON.stringify(arr)},
			        dataType : "json",
//			        contentType : 'application/json', //设置请求头信息，编码为key/value格式（默认可不加） 
					
					
					
//			        type : "POST",
//			        url :config.BaseURL+ "station/addline.html",
//			        xhrFields: {
//						withCredentials: true
//					},
//			        data : JSON.stringify(arr),
//			        dataType : "json",
//			        
//			        contentType : 'application/json;charset=utf-8', //设置请求头信息，编码为JSON数据格式（采用JSON格式时添加） 
			        success : function(result) {
			            if (result.success) {
			            	var count = result.data;
//			            	layer.msg("提交成功", {
//			                    icon : 1
//			                });
							alert("提交成功");
			            	getData(deviceId);
			            	$('.itineraryList ').remove();
			            	drawAllLine();
			            } else {
			            	alert(result.message)
//			                layer.msg(result.message, {
//			                    icon : 5
//			                });
			            }
			        },
			        error : function(errorMsg) {
			        	alert('服务器未响应,请稍后再试');
//			            layer.msg('服务器未响应,请稍后再试', {
//			                icon : 2
//			            });
			        }
			    });
		}
		$('.saveItinerary').click(function(){
			if($('.nowItinerary').children().length<3||$('.nowItinerary').find('.itineraryName').val()==''){
//				layer.msg("路线或路线点不合法", {
//					icon : 2
//			    });
				alert('路线或路线点不合法');
				return;
			}
			var allPoint=[];
			 $('.itineraryGroup').find('.itineraryList').each(function(){
				 	var pointGroup=[];
				 	var id=$(this).attr('id');
					$(this).find('.itineraryPoint').each(function(){
			
						pointGroup.push([$(this).find('.lng').text(),$(this).find('.lat').text()]);
					})
					allPoint.push({
						id:id,name:$(this).find('.itineraryName').val(),
						index:$(this).index(),
						deviceId:deviceId,
//						stationList:pointGroup
					});
				})
				console.log(allPoint)
				postData(allPoint);
		})
		var drawAllLine=function drawAllLine(){
			deletePoint();
			var allPoint=[];
			var linePointArr=[];
			var lineName=[];
			 $('.itineraryGroup').find('.itineraryList').each(function(){
				 	var pointGroup=[];
				 	var pointArr=[];
					$(this).find('.itineraryPoint').each(function(){
						
						pointArr.push(new BMap.Point($(this).find('.lng').text(), $(this).find('.lat').text()));
						pointGroup.push({"lng":$(this).find('.lng').text(),"lat":$(this).find('.lat').text()});
					
					})
					lineName.push($(this).find('.itineraryName').val());
					allPoint.push(pointGroup);
					linePointArr.push(pointArr);
				})
				
				for(var i=0;i<allPoint.length;i++){
					var pointArr=allPoint[i];//获取每一条线路的所有坐标点
					var lineArr=linePointArr[i];
						var point = new BMap.Point(pointArr[0].lng, pointArr[0].lat);
						var opts = {
								"position" : point,    // 指定文本标注所在的地理位置
								"offset"   : new BMap.Size(0, 0)    //设置文本偏移量
							}
						var label = new BMap.Label(lineName[i], opts);  // 创建文本标注对象
						label.setStyle({
						color : "red",
						fontSize : "12px",
						height : "20px",
						padding:"0px 30px 0 2px",
						margin:0,
						lineHeight : "20px",
						fontFamily:"微软雅黑"
					 });
						map.addOverlay(label);
						var polyline = new BMap.Polyline(lineArr, {strokeColor:"#579AFC", strokeWeight:4});   //创建折线
						map.addOverlay(polyline);          //增加折线
				}
		}
		var drawLine=function drawLine(){
			
			
			var nowitinerary=[];
			var lineArr=[];
			$('.nowItinerary').find('.itineraryPoint').each(function(){
				lineArr.push(new BMap.Point($(this).find('.lng').text(), $(this).find('.lat').text()));
				nowitinerary.push({"lng":$(this).find('.lng').text(),"lat":$(this).find('.lat').text()});
			})
		
			
			var point = new BMap.Point(nowitinerary[0].lng, nowitinerary[0].lat);
			map.centerAndZoom(point, mapSize);
			var opts = {
					"position" : point,    // 指定文本标注所在的地理位置
					"offset"   : new BMap.Size(0, 0)    //设置文本偏移量
				}
			var label = new BMap.Label($('.nowItinerary').find('.itineraryName').val(), opts);  // 创建文本标注对象
					label.setStyle({
					color : "red",
					fontSize : "12px",
					height : "20px",
					padding:"0px 30px 0 2px",
					margin:0,
					lineHeight : "20px",
					fontFamily:"微软雅黑"
				 });
			map.addOverlay(label);
			
			var polyline = new BMap.Polyline(lineArr, {strokeColor:"red", strokeWeight:4});   //创建折线
			map.addOverlay(polyline);          //增加折线
			
			
			
			
			var allPoint=[];
			var linePointArr=[];
			var lineName=[];
			 $('.itineraryGroup').find('.itineraryList').each(function(){
				 	if($(this).attr('class').split(' ')[2]!=='nowItinerary'){
				 		var pointGroup=[];
					 	var pointArr=[];
					 	lineName.push($(this).find('.itineraryName').val());
						$(this).find('.itineraryPoint').each(function(){
							
							pointArr.push(new BMap.Point($(this).find('.lng').text(), $(this).find('.lat').text()));
							pointGroup.push({"lng":$(this).find('.lng').text(),"lat":$(this).find('.lat').text()});
						
						})
						allPoint.push(pointGroup);
						linePointArr.push(pointArr);
				 	}
				})
			

				for(var i=0;i<allPoint.length;i++){
					var pointArr=allPoint[i];//获取每一条线路的所有坐标点
					
					var	lineArr=[];
					lineArr=linePointArr[i];
					var point = new BMap.Point(pointArr[0].lng, pointArr[0].lat);
						
						var opts = {
								"position" : point,    // 指定文本标注所在的地理位置
								"offset"   : new BMap.Size(0, 0)    //设置文本偏移量
							}
						var label = new BMap.Label(lineName[i], opts);  // 创建文本标注对象
						label.setStyle({
						color : "red",
						fontSize : "12px",
						height : "20px",
						padding:"0px 30px 0 2px",
						margin:0,
						lineHeight : "20px",
						fontFamily:"微软雅黑"
					 });
						map.addOverlay(label);
						var polyline = new BMap.Polyline(lineArr, {strokeColor:"#579AFC", strokeWeight:4});   //创建折线
						map.addOverlay(polyline);          //增加折线
					
					
					
				}
			
		}
	}

}